package com.dz.syndata.service.impl.device;

import com.dz.syndata.bean.device.DeviceBean;
import com.dz.syndata.domain.server.Sys;
import com.dz.syndata.mapper.one.PrimaryDeviceMapper;
import com.dz.syndata.util.HttpRequest;
import com.google.gson.Gson;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class DeviceDataImpl {
    public  static  DeviceDataImpl mDeviceData;
    public  String url="http://172.168.65.34:8082/kdmService/rest/1.0/kksData?method=getRTDataSnapshot&kksCodes=";
    public static DeviceDataImpl getInstance(){
        if(mDeviceData==null){
            mDeviceData=new DeviceDataImpl();
        }
        return mDeviceData;
    }
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 读取本地excel文件
     * @param mDeviceMapper
     * @return
     * @throws Exception
     */
    public static List<String> redExcel(PrimaryDeviceMapper mDeviceMapper) throws Exception {
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        File file=new File("D:\\dz\\title.xls");
        List<String> list = new ArrayList<>();
        try {
            InputStream inputStream = new FileInputStream(file);

            //创建Excel工作薄
            Workbook work = getWorkbook(inputStream,   file.getName());
            for (int i = 0; i < work.getNumberOfSheets(); i++) {
                sheet = work.getSheetAt(i);
                if (sheet == null) {
                    continue;
                }
                for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                    row = sheet.getRow(j);
                    if (row == null || row.getFirstCellNum() == j) {
                        continue;
                    }
                    List<Object> li = new ArrayList<>();
                    for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                        cell = row.getCell(y);
                        li.add(cell);
                    }
                    list.add(li+"");
                }
            }
            work.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 判断文件格式
     *
     * @param inStr
     * @param fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook workbook = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (".xls".equals(fileType)) {
            workbook = new HSSFWorkbook(inStr);
        } else if (".xlsx".equals(fileType)) {
            workbook = new XSSFWorkbook(inStr);
        } else {
            throw new Exception("请上传excel文件！");
        }
        return workbook;
    }

    public List<DeviceBean> selectDevice(PrimaryDeviceMapper primaryDeviceMapper, RedisTemplate<String,Object> redisTemplate1,RedisTemplate<String,Object> redisTemplate2) {
//        String result="{\"BasicResponse\":{\"succeeded\":1},\"RTDataSets\":[{\"tag\":\"OK\",\"kksCode\":\"EB000HP1MKZ01MK016ZZ02J3ED002AA05\",\"RTDataValues\":[{\"Value\":56.7115,\"Time\":1628578469000}]}]}";
        String result=null;
        List<DeviceBean> mDeviceDataLists = primaryDeviceMapper.findAll();
//        DeviceBean deviceBean=new DeviceBean();
        int index= mDeviceDataLists.size()/500;
        logger.info("deviceInfoServiceImpl->>>分组数:"+index);
        String  res="";
        if(index>0){
            for (int i = 0; i < mDeviceDataLists.size(); i++) {
//                if(i+1%500==0){
//                    logger.info("deviceInfoServiceImpl->>>记录总数:"+i);
//
//                    submitData(res,primaryDeviceMapper,redisTemplate1,redisTemplate2);
//                    res="";
//                }
//                logger.info("deviceInfoServiceImpl->>>i:"+i);
                res=mDeviceDataLists.get(i).getCode();
                submitData(res,primaryDeviceMapper,redisTemplate1,redisTemplate2);
            }
        }else {
            for (int i = 0; i < mDeviceDataLists.size(); i++) {
//                res+=mDeviceDataLists.get(i).getCode()+",";
                res=mDeviceDataLists.get(i).getCode();
                submitData(res,primaryDeviceMapper,redisTemplate1,redisTemplate2);

            }
        }
        return mDeviceDataLists;

    }
    private  void submitData(String res,PrimaryDeviceMapper primaryDeviceMapper, RedisTemplate<String,Object> redisTemplate1,RedisTemplate<String,Object> redisTemplate2){
        logger.info("deviceInfoServiceImpl->>>Url:"+res);

        String   result=HttpRequest.sendGet(url + res, null);
        logger.info("deviceInfoServiceImpl->>>json格式返回："+result);

        if(!result.isEmpty()){
            DeviceBean deviceBean1 = new Gson().fromJson(result, DeviceBean.class);

            if(deviceBean1.getBasicResponse().getSucceeded()==1){
                for (DeviceBean.RTDataSetsBean mRtDataSetsBean: deviceBean1.getRTDataSets()
                ) {
                    logger.info("deviceInfoServiceImpl->>>设备编码返回："+mRtDataSetsBean.getKksCode());

                    try {
                        if (mRtDataSetsBean.getTag().equals("OK")) {
                            for (DeviceBean.RTDataSetsBean.RTDataValuesBean mValuesBean : mRtDataSetsBean.getRTDataValues()) {
                                logger.info("deviceInfoServiceImpl->>>设备编码返回："+mValuesBean.getValue());

                                DeviceBean deviceBean=new DeviceBean();
                                deviceBean.setValue(mValuesBean.getValue() + "");
                                deviceBean.setUpdateTime(mValuesBean.getTime());
                                deviceBean.setCode(mRtDataSetsBean.getKksCode());
                                primaryDeviceMapper.updateDeviceInfo(deviceBean);
                                redisTemplate1.opsForValue().set(mRtDataSetsBean.getKksCode(),mValuesBean.getValue());
                                redisTemplate2.opsForValue().set(mRtDataSetsBean.getKksCode(),mValuesBean.getValue());
                            }
                        }
                        else{
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("异常信息："+e.toString()+"------------->");

                    } finally {
                        //手动释放连接
                        RedisConnectionUtils.unbindConnection(redisTemplate1.getConnectionFactory());
                        RedisConnectionUtils.unbindConnection(redisTemplate2.getConnectionFactory());

                    }
                }
            }
        }
    }
}
